package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component//将该工具类交给spring容器管理
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Movement movement){
        //2.查询当前用户的所有好友
        Long userId = movement.getUserId();
        //3.设置条件
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //4.将可见的好友表记录到关系表中
        for (Friend friend : friends) {
            MovementTimeLine line = new MovementTimeLine();
            //因为目前所有人都可以见到,所以这里就忽略,设置成所有人都可以见
            line.setCreated(System.currentTimeMillis());//发布时间
            line.setFriendId(friend.getFriendId());     //设置好友id
            line.setMovementId(movement.getId());       //设置该条动态的id
            line.setUserId(userId);                     //设置发表动态的用户id
            //5.将可见关系表保存到数据库
            mongoTemplate.save(line);
        }
    }
}
